/*
 * @Author: 吴世扬 18368095041@163.com
 * @Date: 2024-10-15 16:55:51
 * @LastEditors: 吴世扬 18368095041@163.com
 * @LastEditTime: 2024-10-16 07:50:21
 * @FilePath: /react18-vite-admin/src/views/system/DeptManage/components/useForm.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { useState, useEffect } from 'react';
import { FormInstance } from 'antd';
import { immerable } from 'immer';
import { useImmer } from 'use-immer';

import {
    useDepartmentDetail,
    DeptParam
} from '@/service/biz/department/useDepartmentDetail';
import type { DeptTreeItem } from '@/typings/api/department';
import { useEnumStore } from '@/store';

class FormModel extends DeptParam {
    [immerable] = true;
}

export const useForm = (
    formRef: FormInstance,
    parentId: number | undefined,
    detail: DeptTreeItem | undefined,
    open: boolean,
    afterSubmit: () => void
) => {
    const { saveLoading, saveDept } = useDepartmentDetail();

    const [title, setTitle] = useState('新增');

    const [formModel, setFormModel] = useImmer(new FormModel());

    const { deptTreeItems, handleUpdate } = useEnumStore();

    const handleEdit = () => {
        const model = new FormModel();
        if (detail) {
            setTitle('编辑');
            model.id = detail.id;
            model.name = detail.name ?? '';
            model.parentId = detail.parentId ?? -1;
            model.valid = detail.valid ?? false;
        } else if (parentId) {
            setTitle('添加子项');
            model.parentId = parentId ?? -1;
        } else {
            setTitle('新增');
            model.parentId = -1;
        }
        setFormModel(model);
        formRef.setFieldsValue(model);
    };

    const handleSubmit = async () => {
        console.log(formModel);
        await saveDept({
            id: formModel.id,
            name: formModel.name,
            valid: formModel.valid,
            parentId: formModel.parentId !== -1 ? formModel.parentId : undefined
        });
        afterSubmit();
    };

    useEffect(() => {
        if (open) {
            formRef.resetFields();
            handleUpdate(['deptTreeItems']);
            handleEdit();
        }
    }, [open]);

    return {
        title,
        handleEdit,
        handleSubmit,
        formModel,
        setFormModel,
        deptTreeItems,
        saveLoading
    };
};
